import React, {Component} from 'react';
import {Dimensions, StyleSheet, Text} from 'react-native';
import ImageViewer from 'react-native-image-zoom-viewer';
import {Dialog, TouchableOpacity, View} from 'react-native-ui-lib';
import {downLoadImage, logger} from '../../utils/util';
import {check, PERMISSIONS, request} from 'react-native-permissions';
import {Icon} from '../components';

let {width, height} = Dimensions.get('window');

if (width > height) {
  let temp = width;
  width = height;
  height = temp;
}
/**
 * 图片预览
 */
export default class ImageViewerDialog extends Component {

  constructor(props) {
    super(props);
    this.state = {
      isOpen: false,
      currentMessageImage: '',
      selectIndex: 0,
    };
  }

  show = (currentMessageImage, selectIndex) => {
    this.setState({isOpen: true, currentMessageImage, selectIndex});
  };

  dismiss = () => {
    this.setState({isOpen: false});
  };

  renderPannableHeader = props => {
    return (
      <TouchableOpacity row centerV padding-10 onPress={this.dismiss}>
        <Icon type="AntDesign" name={"close"} size={20} color={"white"}/>
      </TouchableOpacity>

    )
  }

  checkCameraPermission = async () => {
    return new Promise(async (resolve, reject) => {
      //1.检测定位权限
      let store_permission = await check(Platform.select({
        android: PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE,
        ios: PERMISSIONS.IOS.PHOTO_LIBRARY
      })).catch(logger)
      //2.无权限，则请求获取群贤
      if (store_permission !== "granted") {
        store_permission = await request(Platform.select({
          android: PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE,
          ios: PERMISSIONS.IOS.PHOTO_LIBRARY
        })).catch(logger)
      }

      if (store_permission === "granted") {
        resolve(true)
      } else {
        Toast.show("保存图片需要存储权限，请先开启")
        resolve(false)
      }
    })
  }
  /**
   * 1.设置modal内容居中，背景透明
   * 2.设置内容视图背景色，圆角
   * @returns {*}
   */
  render() {
    const {isOpen, currentMessageImage, selectIndex} = this.state;
    logger('数据', currentMessageImage);
    return (
      <Dialog
        migrate
        containerStyle={styles.roundedDialog}
        visible={isOpen}
        bottom
        width={"100%"}
        height={"100%"}
        onDismiss={this.dismiss}
        renderPannableHeader={this.renderPannableHeader}
      >

        <ImageViewer
          style={{width, height}}
          backgroundColor={'rgba(0,0,0,0)'}
          renderIndicator={(currentIndex,allSize) => {
            if(IsNullOrEmpty(currentMessageImage)||currentMessageImage.length==1)
            {
              return <View/>;
            }
            return <View style={styles.count}><Text style={styles.countText}>{currentIndex}/{allSize}</Text></View>
          }}
          maxOverflow={0}
          flipThreshold={0}
          enableSwipeDown={true}
          menuContext={{'saveToLocal':'保存', 'cancel': '取消'}}
          onClick={() => this.setState({isOpen: false})}
          onSave={async (url) => {
            const hasPermission = await this.checkCameraPermission()
            if (!hasPermission) {
              return
            }
            downLoadImage(url)
            this.dismiss()
          }}
          onSwipeDown={(a) => this.setState({isOpen: false})}
          renderFooter={() => {
            return (
              <View style={{
                justifyContent: 'center',
                alignItems: 'center',
                width,
                height: 'auto',
                flex: 1,
              }}>
                <Text style={{color: 'white',fontSize:12, lineHeight: 100}}>下滑图片到此可关闭</Text>
              </View>
            );
          }}
          index={selectIndex}
          onCancel={() => this.setState({isOpen: false})}
          imageUrls={currentMessageImage}/>

      </Dialog>
    );
  }
}


const styles = StyleSheet.create({
  roundedDialog: {
    backgroundColor: "black"
  },
  count: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 10,
    zIndex: 13,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'transparent'
  },
  countText: {
    color: 'white',
    fontSize: 16,
    backgroundColor: 'transparent',
    textShadowColor: 'rgba(0, 0, 0, 0.3)',
    textShadowOffset: {
      width: 0,
      height: 0.5
    },
    textShadowRadius: 0
  }

});


